import React, { useMemo, useState } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Space,
  Table,
  Tag,
  Popover,
  Modal,
  Steps,
  message,
} from 'antd';

// 续费记录页面（模仿 admin-web/src/views/order/RenewalRecord.vue 的结构与交互）
// 功能：查询、设备列表弹窗、步骤详情、续费确认

const payTypeMap = {
  '1': '支付宝',
  '2': '微信',
  '3': 'Stripe',
};

const subscriptionTypeMap = {
  1: 'Monthly',
  2: 'Yearly',
};

const stateMap = {
  0: { text: '待处理', color: 'default' },
  1: { text: '处理中', color: 'processing' },
  2: { text: '已完成', color: 'success' },
  5: { text: '已取消', color: 'error' },
};

const mockData = [
  {
    id: 101,
    userName: 'alice',
    nickName: 'Alice',
    payAccount: 'alice@pay.com',
    orderNumber: 'RN202409010001',
    stripeSubscriptionPayType: 1,
    rentEquipment: [
      { name: '挖矿设备 A1', equipmentNo: 'EQ-1001', date: '2024-08-10 ~ 2024-09-10' },
      { name: '挖矿设备 A2', equipmentNo: 'EQ-1002', date: '2024-08-10 ~ 2024-09-10' },
    ],
    state: 0,
    payType: '3',
    createTime: '2024-09-01 10:15:00',
  },
  {
    id: 102,
    userName: 'bob',
    nickName: 'Bob',
    payAccount: 'bob@pay.com',
    orderNumber: 'RN202409020123',
    stripeSubscriptionPayType: 2,
    rentEquipment: [
      { name: '挖矿设备 B1', equipmentNo: 'EQ-2011', date: '2024-07-02 ~ 2025-07-01' },
    ],
    state: 1,
    payType: '1',
    createTime: '2024-09-02 12:00:00',
  },
  {
    id: 103,
    userName: 'carol',
    nickName: 'Carol',
    payAccount: 'carol@pay.com',
    orderNumber: 'RN202409030045',
    stripeSubscriptionPayType: 1,
    rentEquipment: [
      { name: '挖矿设备 C1', equipmentNo: 'EQ-3015', date: '2024-08-03 ~ 2024-09-03' },
      { name: '挖矿设备 C2', equipmentNo: 'EQ-3016', date: '2024-08-03 ~ 2024-09-03' },
      { name: '挖矿设备 C3', equipmentNo: 'EQ-3017', date: '2024-08-03 ~ 2024-09-03' },
    ],
    state: 2,
    payType: '2',
    createTime: '2024-09-03 09:35:27',
  },
];

const RenewalRecord = () => {
  const [form] = Form.useForm();
  const [dataSource, setDataSource] = useState(mockData);
  const [detailVisible, setDetailVisible] = useState(false);
  const [renewVisible, setRenewVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState(null);

  const onSearch = () => {
    const values = form.getFieldsValue();
    const { userName, orderNumber, payAccount, payType, state } = values;
    const filtered = mockData.filter((item) => {
      const conds = [
        !userName || String(item.userName).includes(userName),
        !orderNumber || String(item.orderNumber).includes(orderNumber),
        !payAccount || String(item.payAccount).includes(payAccount),
        !payType || String(item.payType) === String(payType),
        state === undefined || state === '' || String(item.state) === String(state),
      ];
      return conds.every(Boolean);
    });
    setDataSource(filtered);
  };

  const onReset = () => {
    form.resetFields();
    setDataSource(mockData);
  };

  const onShowDetail = (row) => {
    setCurrentRow(row);
    setDetailVisible(true);
  };

  const onRevoke = (row) => {
    message.success(`已撤销订单 ${row.orderNumber}`);
    setDataSource((prev) => prev.map((r) => (r.id === row.id ? { ...r, state: 5 } : r)));
  };

  const onRenew = (row) => {
    setCurrentRow(row);
    setRenewVisible(true);
  };

  const doConfirmRenew = () => {
    if (!currentRow) return;
    message.success(`订单 ${currentRow.orderNumber} 续费确认成功`);
    setRenewVisible(false);
    // 模拟状态流转为处理中
    setDataSource((prev) => prev.map((r) => (r.id === currentRow.id ? { ...r, state: 1 } : r)));
  };

  const equipmentColumns = [
    { title: '设备名称', dataIndex: 'name', key: 'name' },
    { title: '设备编号', dataIndex: 'equipmentNo', key: 'equipmentNo' },
    { title: '租期', dataIndex: 'date', key: 'date' },
  ];

  const columns = useMemo(
    () => [
      { title: '用户名', dataIndex: 'userName', key: 'userName' },
      { title: '昵称', dataIndex: 'nickName', key: 'nickName' },
      { title: '支付账号', dataIndex: 'payAccount', key: 'payAccount' },
      { title: '订单号', dataIndex: 'orderNumber', key: 'orderNumber' },
      {
        title: '订阅类型',
        dataIndex: 'stripeSubscriptionPayType',
        key: 'stripeSubscriptionPayType',
        render: (val) => subscriptionTypeMap[val] || '-',
      },
      {
        title: '设备列表',
        dataIndex: 'rentEquipment',
        key: 'rentEquipment',
        render: (equipList) => (
          <Popover
            title="设备列表"
            content={
              <Table
                size="small"
                columns={equipmentColumns}
                dataSource={equipList.map((e, idx) => ({ ...e, key: idx }))}
                pagination={false}
              />
            }
          >
            <Button type="link">查看设备</Button>
          </Popover>
        ),
      },
      {
        title: '状态',
        dataIndex: 'state',
        key: 'state',
        render: (st) => {
          const cfg = stateMap[st] || { text: st, color: 'default' };
          return <Tag color={cfg.color}>{cfg.text}</Tag>;
        },
      },
      {
        title: '支付方式',
        dataIndex: 'payType',
        key: 'payType',
        render: (val) => payTypeMap[val] || '-',
      },
      { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
      {
        title: '操作',
        key: 'action',
        render: (_, row) => (
          <Space>
            <Button type="primary" onClick={() => onShowDetail(row)}>
              详情
            </Button>
            {row.state === 0 && (
              <Button danger onClick={() => onRevoke(row)}>
                撤销
              </Button>
            )}
            {row.state === 1 && (
              <Button onClick={() => onRenew(row)}>续费</Button>
            )}
          </Space>
        ),
      },
    ],
    []
  );

  return (
    <Card title="续费记录">
      <Form form={form} layout="inline" style={{ marginBottom: 12 }}>
        <Form.Item label="用户名" name="userName">
          <Input allowClear placeholder="输入用户名" />
        </Form.Item>
        <Form.Item label="订单号" name="orderNumber">
          <Input allowClear placeholder="输入订单号" />
        </Form.Item>
        <Form.Item label="支付账号" name="payAccount">
          <Input allowClear placeholder="输入支付账号" />
        </Form.Item>
        <Form.Item label="支付方式" name="payType">
          <Select allowClear style={{ width: 140 }} placeholder="选择支付方式">
            <Select.Option value="1">支付宝</Select.Option>
            <Select.Option value="2">微信</Select.Option>
            <Select.Option value="3">Stripe</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label="状态" name="state">
          <Select allowClear style={{ width: 140 }} placeholder="选择状态">
            <Select.Option value={0}>待处理</Select.Option>
            <Select.Option value={1}>处理中</Select.Option>
            <Select.Option value={2}>已完成</Select.Option>
            <Select.Option value={5}>已取消</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" onClick={onSearch}>
              查询
            </Button>
            <Button onClick={onReset}>重置</Button>
          </Space>
        </Form.Item>
      </Form>

      <Table
        rowKey="id"
        columns={columns}
        dataSource={dataSource}
        pagination={{ pageSize: 10 }}
      />

      {/* 详情步骤弹窗 */}
      <Modal
        title="续费详情"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={<Button onClick={() => setDetailVisible(false)}>关闭</Button>}
      >
        <Steps
          size="small"
          current={currentRow && (currentRow.state === 0 ? 0 : currentRow.state === 1 ? 1 : 2)}
          items={[
            { title: '提交申请' },
            { title: '渠道扣款' },
            { title: '续费完成' },
          ]}
        />
        {currentRow ? (
          <div style={{ marginTop: 16 }}>
            <div>订单号：{currentRow.orderNumber}</div>
            <div>订阅类型：{subscriptionTypeMap[currentRow.stripeSubscriptionPayType]}</div>
            <div>支付方式：{payTypeMap[currentRow.payType]}</div>
            <div>创建时间：{currentRow.createTime}</div>
          </div>
        ) : null}
      </Modal>

      {/* 续费确认弹窗 */}
      <Modal
        title="确认续费"
        open={renewVisible}
        onCancel={() => setRenewVisible(false)}
        onOk={doConfirmRenew}
        okText="确认"
        cancelText="取消"
      >
        <p>确认对选中订单执行续费操作？</p>
        {currentRow ? (
          <div>
            <div>订单号：{currentRow.orderNumber}</div>
            <div>订阅类型：{subscriptionTypeMap[currentRow.stripeSubscriptionPayType]}</div>
          </div>
        ) : null}
      </Modal>
    </Card>
  );
};

export default RenewalRecord;